package com.joolun.script.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joolun.script.entity.WxUserExt;
import com.joolun.script.mapper.WxUserExtMapper;
import com.joolun.script.service.WxUserExtService;
import com.joolun.weixin.entity.WxUser;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户扩展表
 *
 * @author 臣服
 * @date 2022-01-12 10:52:45
 */
@Service
public class WxUserExtServiceImpl extends ServiceImpl<WxUserExtMapper, WxUserExt> implements WxUserExtService {

    @Override
    public WxUserExt getByUserId(String wxUserId) {
        LambdaQueryWrapper<WxUserExt> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WxUserExt::getUserId, wxUserId);
        queryWrapper.last("limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public WxUserExt addExt(WxUser wxUser) {
        WxUserExt ext = new WxUserExt();
        ext.setCreateTime(LocalDateTime.now());
        ext.setIsAdmin("N");
        ext.setUserId(wxUser.getId());
        baseMapper.insert(ext);
        return ext;
    }

    @Override
    public Boolean updateByUserId(String id, String school) {
        WxUserExt userExt = getByUserId(id);
        if (Objects.isNull(userExt)) {
            return Boolean.FALSE;
        }
        userExt.setSchool(school);
        return baseMapper.updateById(userExt) > 0;
    }

    @Override
    public List<WxUserExt> queryByUserIdList(List<String> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<WxUserExt> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(WxUserExt::getUserId, userIdList);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, WxUserExt> getExtMap(List<WxUserExt> userExtList) {
        if (CollectionUtils.isEmpty(userExtList)) {
            return Collections.emptyMap();
        }
        return userExtList.stream().collect(Collectors.toMap(WxUserExt::getUserId, o -> o));
    }

}
